﻿<Cmdlet(VerbsLifecycle.Invoke, "SqlUpdate")>
<CmdletBinding(DefaultParameterSetName:="Query")>
Public Class InvokeSqlUpdate
    Inherits PSCmdlet

    <Parameter(Mandatory:=True, Position:=1, ParameterSetName:="Query")>
    Public Property Query As String
    <Parameter(Position:=2, ParameterSetName:="Query", ValueFromPipeline:=True)>
    Public Property Parameters As Hashtable

    <Parameter(Mandatory:=True, ParameterSetName:="Command", position:=1, ValueFromPipeline:=True)>
    Public Property Command As IDbCommand

    <Parameter>
    Public Property ConnectionName As String = "Default"

    <Parameter(ParameterSetName:="Query")>
    Public Property CommandTimeout As Integer = -1

    Protected Overrides Sub ProcessRecord()
        MyBase.ProcessRecord()

        If Not DBInfo.Connections.ContainsKey(Me.ConnectionName) Then
            WriteWarning(DBInfo.NoConnection(Me.ConnectionName))
            Exit Sub
        End If

        DBInfo.ProcessHashTable(Me.Parameters)
        DBInfo.Connections(Me.ConnectionName).ClearMessages()

        Select Case ParameterSetName
            Case "Query"
                Using cmd As IDbCommand = DBInfo.Connections(Me.ConnectionName).GetCommand(Query, CommandTimeout, Parameters)
                    WriteObject(cmd.ExecuteNonQuery)
                End Using
            Case "Command"
                DBInfo.Connections(Me.ConnectionName).AttachTransaction(Command)
                WriteObject(Command.ExecuteNonQuery)
        End Select
    End Sub

End Class
